import os
import time

import wx
import wx.lib.agw.aui as aui

#from common import EVT_LOG_EVENT
from common.event_dispatcher import EventDispatcher, EVT_MY_EVENT
from gui.dlg_config import ConfigDialog
from gui.mainframe_left import LeftNotebook
from gui.mainframe_log_panel import LogPanel
from gui.mainframe_right import RightNotebook
from gui.widgets.widget_web import WebPanel
from gui.gui_logic import LoginThread


class MainFrame(wx.Frame):
    def __init__(self, *args, **kw):

        super().__init__(parent=None, title="aiTrader 7.0.0 - AI智能量化投研平台", style=wx.DEFAULT_FRAME_STYLE | wx.MAXIMIZE_BOX)
        self.Bind(EVT_MY_EVENT, self.on_event)
        self.Maximize()
        # 设置程序图标
        # icon_file = "gui/imgs/logo.ico"
        # icon = wx.Icon(icon_file, wx.BITMAP_TYPE_ICO)
        # self.SetIcon(icon)

        self.init_statusbar()
        self.init_menu_bar()
        #self.init_main_ui()
        self.init_toolbar()
        #self.init_aui()

        self.web = None
        wx.CallAfter(self.init_aui)

        self.init_sys()

    def on_event(self, event):
        # 分发事件给所有观察者
        data = event.GetData()
        id = data.get('id',-1)
        if id == 1:  # 登录成功
            show_name = data.get('show_name',' [用户未登录]')
            self.SetTitle(self.GetTitle() + f' - {show_name}')


        #print(EventDispatcher()._observers)
        for observer in EventDispatcher()._observers:
            observer(event.GetData())

    def init_sys(self):
        LoginThread().start()


    def init_aui(self):
        # 创建AUI管理器 - 确保使用 wx.lib.agw.aui.AuiManager
        self.mgr = aui.AuiManager(self)
        #self.mgr.SetAGWW()

        #设置AUI样式 - 使用AGW特有的方法
        self.mgr.SetAGWFlags(
            aui.AUI_MGR_DEFAULT |
            aui.AUI_MGR_TRANSPARENT_DRAG |
            aui.AUI_MGR_ALLOW_ACTIVE_PANE |
            aui.AUI_MGR_RECTANGLE_HINT
        )

        # 创建左侧notebook
        self.left_notebook = LeftNotebook(self)

        # 创建右侧notebook
        self.right_notebook = RightNotebook(self)


        # 创建日志面板
        self.log_panel = LogPanel(self)
        #print('注册日志观察者。。。')
        EventDispatcher().add_observer(self.log_panel.handle_log)

        # 添加面板到AUI管理器
        self.mgr.AddPane(self.left_notebook,
                         aui.AuiPaneInfo().Name("left_pane").Left().Layer(0)
                         .Caption("功能导航").CloseButton(False).PinButton(True)
                         .BestSize(170, -1))

        self.mgr.AddPane(self.right_notebook,
                         aui.AuiPaneInfo().Name("center_pane").CenterPane())

        self.mgr.AddPane(self.log_panel,
                         aui.AuiPaneInfo().Name("log_pane").Bottom()
                         .Caption("日志输出").CloseButton(False).BestSize(-1, 150))

        # 更新AUI管理器
        self.mgr.Update()

        # 绑定事件
        self.Bind(wx.EVT_CLOSE, self.on_close)

    def on_close(self, event):
        self.mgr.UnInit()
        event.Skip()




    def init_menu_bar(self):
        # 创建窗口面板
        menuBar = wx.MenuBar(style=wx.MB_DOCKABLE)
        self.SetMenuBar(menuBar)
        self.SetMinSize((1618, 900))

        setting = wx.Menu()
        menuBar.Append(setting, "&设置")
        params_conf = wx.MenuItem(setting, 9, "&参数配置")
        setting.Append(params_conf)
        self.Bind(wx.EVT_MENU, self.on_params_conf, params_conf)

        tools = wx.Menu()
        menuBar.Append(tools, "&工具")


        tools.AppendSeparator()

        website = wx.MenuItem(tools, 3, "&AI量化实验室官网")
        tools.Append(website)
        self.Bind(wx.EVT_MENU, self.on_menu, website)

        mall = wx.MenuItem(tools, 8, "&策略优选")
        tools.Append(mall)
        self.Bind(wx.EVT_MENU, self.on_menu, mall)

        strategy = wx.MenuItem(tools, 88, "&创建策略")
        tools.Append(strategy)
        self.Bind(wx.EVT_MENU, self.on_menu, strategy)



        # Now a help menu for the about item
        helpMenu = wx.Menu()
        aboutItem = helpMenu.Append(10, "关于")
        menuBar.Append(helpMenu, "&帮助")

    def on_menu(self, event):
        from config import HOST
        #HOST = 'http://127.0.0.1:5000'
        from config import global_config
        print(event.Id)
        if event.Id == 9:
            self.on_params_conf(event)
            return
        if event.Id == 10:
            self.OnAbout(event)
            return

        if event.Id == 1:
            self.show_page('http://bbs.ailabx.com','量化社区-知识库')
        if event.Id == 3:
            self.show_page(f'{HOST}?token={global_config.user_token}', '官网')

        if event.Id == 8:
            self.show_page(f"{HOST}/mall?token={global_config.user_token}",'策略优选')

        if event.Id == 88:
            self.show_page(f"{HOST}/quant/create_strategy?token={global_config.user_token}",'策略优选')


    def show_page(self, url, title):
        if not self.web:
            self.web = WebPanel(self.right_notebook)
            self.right_notebook.AddPage(self.web, "浏览器")

        page_index = self.right_notebook.FindPage(self.web)  # 找到 self.web 所在的页索引
        self.right_notebook.SetSelection(page_index)  # 切换到该页
        self.web.show_url(url)
        page_title = title
        self.right_notebook.SetPageText(page_index, page_title)

    def on_params_conf(self, event):

        dlg = ConfigDialog(self)
        if dlg.ShowModal() == wx.ID_OK:
            print("配置已保存")
        dlg.Destroy()

    def OnAbout(self, event):
        wx.MessageBox(
            "公众号: 七年实现财富自由",
            "关于 aiTrader 智能量化投研平台",
            wx.OK | wx.ICON_INFORMATION,
        )

    def init_toolbar(self):
        # 创建工具栏
        toolbar = self.CreateToolBar(style=wx.TB_HORIZONTAL|wx.TB_TEXT)
        script_dir = os.path.dirname(os.path.abspath(__file__))

        # 加载自定义配置图标 - 使用相对路径 img/config.png
        toolbar.SetToolBitmapSize((20, 20))
        config_path = os.path.join(script_dir,"imgs", "config.png")
        list_path = os.path.join(script_dir,"imgs", "群组.png")

        # 尝试加载自定义图标
        config_bmp = wx.Bitmap(config_path, wx.BITMAP_TYPE_PNG)
        stratgey_bmp = wx.Bitmap(os.path.join(script_dir,"imgs", "策略.png"), wx.BITMAP_TYPE_PNG)

        web_bmp = wx.Bitmap(os.path.join(script_dir, "imgs", "lab.png"), wx.BITMAP_TYPE_PNG)
        mall_bmp = wx.Bitmap(os.path.join(script_dir, "imgs", "mall.png"), wx.BITMAP_TYPE_PNG)
        bbs_bmp = wx.Bitmap(os.path.join(script_dir, "imgs", "bbs.png"), wx.BITMAP_TYPE_PNG)

        toolbar.AddSeparator()

        toolbar.AddTool(3, "AI量化实验室官网", web_bmp, "打开AI实验室")
        toolbar.AddTool(8, "策略优选", mall_bmp, "打开AI实验室商城")
        toolbar.AddTool(1, "量化论坛-知识库", bbs_bmp, "打开知识库")

        toolbar.AddTool(9, "系统配置", config_bmp, "打开系统配置")
        toolbar.AddTool(88, "创建策略", stratgey_bmp, "免费创建策略")


        self.Bind(wx.EVT_TOOL, self.on_menu)
        toolbar.Realize()

    def init_statusbar(self):
        version = '7.0.0'
        self.statusBar = self.CreateStatusBar()  # 创建状态条
        self.statusBar.SetFieldsCount(3)
        self.statusBar.SetStatusWidths([-3, -1, -1])
        t = time.localtime(time.time())
        self.SetStatusText("欢迎使用AI智能量化投研平台！请关注公众号: 七年实现财富自由", 0)
        self.SetStatusText("当前版本：%s" % str(version), 1)
        self.SetStatusText(time.strftime("%Y-%m-%d %I:%M:%S", t), 2)

        self.sys_timer = wx.Timer(self, id=wx.ID_ANY)
        self.sys_timer.Start(1000)
        self.Bind(wx.EVT_TIMER, self._update_sys_time, self.sys_timer)

    def _update_sys_time(self, event):
        t = time.localtime(time.time())
        self.SetStatusText(time.strftime("%Y-%m-%d %I:%M:%S", t), 2)

    def init_right_panel(self):
        right_panel = wx.Panel(self.main_panel)
        self.right_panel = right_panel
        right_sizer = wx.BoxSizer(wx.VERTICAL)

        # 右上方Notebook
        self.top_notebook = wx.Notebook(right_panel)

        # ...
        # 下方可折叠日志面板
        self.log_panel = LogPanel(right_panel)
        self.log_panel.SetMinSize((-1, 200))  # 设置最小高度为200


        # # 设置日志面板布局
        # log_sizer = wx.BoxSizer(wx.VERTICAL)
        # log_sizer.Add(self.log_panel, 1, wx.EXPAND)


        right_sizer.Add(self.top_notebook, 1, wx.EXPAND)
        right_sizer.Add(self.log_panel, 0, wx.EXPAND)
        right_panel.SetSizer(right_sizer)


        self.main_sizer.Add(right_panel, 1, wx.EXPAND)

